package com.translation.gutenberg;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.translation.ArrayInterator;
import com.translation.dao.Batch;

public class WordImporter extends GutenbergImporter {

	private String locale_id;

	public WordImporter(String locale_id) {
		this.locale_id = locale_id;
		System.out.println(locale_id);
	}

	public static void main(String[] args) {
		System.out.println("Start:" + new Date());
		for (int i = 0; i < args.length; i += 2) {
			try {
				WordImporter updater = new WordImporter(args[i + 1]);
				updater.importDirs(args[i]);
			} catch (Exception e) {
				System.out.println(args[i] + ":" + args[i + 1] + "\n");
				e.printStackTrace();
			}
		}
		System.out.println("End:" + new Date());
	}

	public void batch() {
		try {
			Set<Entry<String, Integer>> entries = catalog.entrySet();
			Entry<String, Integer>[] values = new Entry[entries.size()];
			entries.toArray(values);

			Comparator<Entry<String, Integer>> comp = new Comparator<Entry<String, Integer>>() {

				@Override
				public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
					return (int) (o2.getValue() - o1.getValue());
				}

			};

			Arrays.sort(values, comp);

			int max = values.length < 30000 ? values.length : 30000;
			if (max >= 15000) {
				int begin = 15000;
				int to = 30000;
				values = Arrays.copyOfRange(values, begin, to);
			} else {
				values = new Entry[0];
			}

			Iterator<Entry<String, Integer>> it = new ArrayInterator<Entry<String, Integer>>(values);

			/*
			Map.Entry<String, Integer> entry = null;
			while ((entry = it.next()) != null) {
				System.out.println(entry);
			}
			*/

			Batch batch = getBatch(it, this.locale_id);
			dao.namedBatch("word", batch);
			System.out.println("Batch:" + new Date());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.shutdown();
		}
	}
	private Batch getBatch(final Iterator<Map.Entry<String, Integer>> it, final String locale_id) {

		return new Batch() {

			private Map.Entry<String, Integer> entry;

			@Override
			public void setParams(PreparedStatement st) throws SQLException {
				int index = 1;
				String word = entry.getKey();
				Integer freq = entry.getValue();
				st.setString(index++, locale_id);
				st.setInt(index++, freq);
				st.setString(index++, word);
			}

			@Override
			public boolean result(int[] result, PreparedStatement st) throws SQLException {
				return true;
			}

			@Override
			public boolean next() throws SQLException {
				entry = it.next();
				return entry != null;
			}

			@Override
			public int getSize() {
				return 100;
			}

			@Override
			public void error(SQLException e) {
				if (entry != null) {
					System.out.println("Near:" + entry);
				}
			}
		};
	}

}
